import { ref } from 'vue'
import { supabase } from '../config/supabase'

export const useDocuments = () => {
  const documents = ref([])
  const loading = ref(false)
  const error = ref(null)

  const fetchDocuments = async () => {
    try {
      loading.value = true
      const { data, error: fetchError } = await supabase
        .from('documents')
        .select('*')
        .order('created_at', { ascending: false })

      if (fetchError) throw fetchError
      documents.value = data
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  const createDocument = async (document) => {
    try {
      loading.value = true
      const { data, error: createError } = await supabase
        .from('documents')
        .insert([document])
        .select()
        .single()

      if (createError) throw createError
      return data
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  const updateDocument = async (id, updates) => {
    try {
      loading.value = true
      const { data, error: updateError } = await supabase
        .from('documents')
        .update(updates)
        .eq('id', id)
        .select()
        .single()

      if (updateError) throw updateError
      return data
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  const deleteDocument = async (id) => {
    try {
      loading.value = true
      const { error: deleteError } = await supabase
        .from('documents')
        .delete()
        .eq('id', id)

      if (deleteError) throw deleteError
      return true
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  return {
    documents,
    loading,
    error,
    fetchDocuments,
    createDocument,
    updateDocument,
    deleteDocument
  }
}
